#include "preHeader.h"
#include "InstCfgMgr.h"
#include "Session/DBPSession.h"
#include "Session/DBPHelper.h"

InstCfgMgr::InstCfgMgr()
{
}

InstCfgMgr::~InstCfgMgr()
{
}

bool InstCfgMgr::LoadDataFromDB()
{
	NetPacket rpcReqPck(CDBP_LOAD_ALL_INST_CFG_DATA);
	auto errCode = DBPHelper::RPCBlockInvoke(&sDBPSession, rpcReqPck,
		[=](INetStream& pck) {
		while (!pck.IsReadableEmpty()) {
			inst_configure instCfg;
			LoadFromINetStream(instCfg, pck);
			m_instCfgs.emplace(instCfg.cfgID, std::move(instCfg));
		}
	}, sDBPSessionUpdate4RPCBlockInvoke);
	if (errCode != RPCErrorNone) {
		return false;
	}
	return true;
}

const std::string& InstCfgMgr::GetInstCfgVal(uint32 cfgId) const
{
	auto itr = m_instCfgs.find(cfgId);
	return itr != m_instCfgs.end() ? itr->second.cfgValue : emptyString;
}

void InstCfgMgr::SaveInstCfgVal(uint32 cfgId, const std::string& cfgVal)
{
	auto itr = m_instCfgs.find(cfgId);
	if (itr != m_instCfgs.end()) {
		itr->second.cfgValue = cfgVal;
	} else {
		inst_configure instCfg;
		instCfg.cfgID = cfgId, instCfg.cfgValue = cfgVal;
		itr = m_instCfgs.emplace(instCfg.cfgID, std::move(instCfg)).first;
	}
	NetPacket rpcReqPck(CDBP_SAVE_INST_CFG_DATA);
	SaveToINetStream(itr->second, rpcReqPck);
	sDBPSession.RPCInvoke(rpcReqPck);
}
